"use client"

import { useState } from "react"
import { Search, Filter, Download, Eye, Calendar } from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { format } from "date-fns"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import type { DateRange } from "react-day-picker"

// 修改生成模拟历史记录数据的函数
const generateHistoryData = () => {
  const classes = [
    "计算机科学1班",
    "计算机科学2班",
    "软件工程1班",
    "软件工程2班",
    "电子工程1班",
    "电子工程2班",
    "人工智能1班",
  ]
  const subjects = [
    "高等数学",
    "大学英语",
    "程序设计基础",
    "数据结构",
    "计算机网络",
    "操作系统",
    "数据库原理",
    "软件工程",
  ]
  const teachers = ["王教授", "李教授", "张教授", "刘教授", "陈教授", "周教授", "吴教授", "赵教授"]

  return Array.from({ length: 50 }, (_, i) => {
    const id = i + 1
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))

    const classIndex = Math.floor(Math.random() * classes.length)
    const subjectIndex = Math.floor(Math.random() * subjects.length)
    const teacherIndex = Math.floor(Math.random() * teachers.length)

    const startHour = 8 + Math.floor(Math.random() * 10)
    const startTime = `${startHour.toString().padStart(2, "0")}:00`
    const endTime = `${(startHour + 2).toString().padStart(2, "0")}:00`

    const attendanceRate = Math.floor(Math.random() * 20) + 80
    const attentionScore = Math.floor(Math.random() * 30) + 70
    const participationRate = Math.floor(Math.random() * 25) + 75

    return {
      id,
      date: format(date, "yyyy-MM-dd"),
      class: classes[classIndex],
      subject: subjects[subjectIndex],
      teacher: teachers[teacherIndex],
      time: `${startTime}-${endTime}`,
      duration: "100分钟",
      attendanceRate: `${attendanceRate}%`,
      attentionScore: attentionScore,
      participationRate: `${participationRate}%`,
      status: attentionScore > 85 ? "优秀" : attentionScore > 75 ? "良好" : "一般",
    }
  }).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
}

const historyData = generateHistoryData()

export function HistoryRecords() {
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedClass, setSelectedClass] = useState("all")
  const [selectedSubject, setSelectedSubject] = useState("all")
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: new Date(new Date().setDate(new Date().getDate() - 30)),
    to: new Date(),
  })

  // 过滤历史记录数据
  const filteredHistory = historyData.filter((record) => {
    const matchesSearch =
      record.class.includes(searchTerm) || record.subject.includes(searchTerm) || record.teacher.includes(searchTerm)

    const matchesClass = selectedClass === "all" || record.class.includes(selectedClass)
    const matchesSubject = selectedSubject === "all" || record.subject === selectedSubject

    let matchesDate = true
    if (dateRange?.from) {
      const recordDate = new Date(record.date)
      const from = new Date(dateRange.from)
      from.setHours(0, 0, 0, 0)

      if (dateRange.to) {
        const to = new Date(dateRange.to)
        to.setHours(23, 59, 59, 999)
        matchesDate = recordDate >= from && recordDate <= to
      } else {
        matchesDate = recordDate.toDateString() === from.toDateString()
      }
    }

    return matchesSearch && matchesClass && matchesSubject && matchesDate
  })

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>历史课堂记录</CardTitle>
          <CardDescription>查看过去课堂的详细数据和表现</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-6 flex flex-col gap-4 sm:flex-row">
            <div className="flex flex-1 items-center gap-2">
              <div className="relative flex-1">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  type="search"
                  placeholder="搜索班级、科目或教师..."
                  className="pl-8"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              {/* 修改班级选择下拉菜单 */}
              <Select value={selectedClass} onValueChange={setSelectedClass}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue placeholder="选择班级" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有班级</SelectItem>
                  <SelectItem value="计算机科学">计算机科学</SelectItem>
                  <SelectItem value="软件工程">软件工程</SelectItem>
                  <SelectItem value="电子工程">电子工程</SelectItem>
                  <SelectItem value="人工智能">人工智能</SelectItem>
                </SelectContent>
              </Select>

              {/* 修改科目选择下拉菜单 */}
              <Select value={selectedSubject} onValueChange={setSelectedSubject}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue placeholder="选择科目" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有科目</SelectItem>
                  <SelectItem value="高等数学">高等数学</SelectItem>
                  <SelectItem value="大学英语">大学英语</SelectItem>
                  <SelectItem value="程序设计基础">程序设计基础</SelectItem>
                  <SelectItem value="数据结构">数据结构</SelectItem>
                  <SelectItem value="计算机网络">计算机网络</SelectItem>
                </SelectContent>
              </Select>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" className={cn("w-[300px] justify-start text-left font-normal")}>
                    <Calendar className="mr-2 h-4 w-4" />
                    {dateRange?.from ? (
                      dateRange.to ? (
                        <>
                          {format(dateRange.from, "LLL dd, y")} - {format(dateRange.to, "LLL dd, y")}
                        </>
                      ) : (
                        format(dateRange.from, "LLL dd, y")
                      )
                    ) : (
                      <span>选择日期范围</span>
                    )}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <CalendarComponent
                    initialFocus
                    mode="range"
                    defaultMonth={dateRange?.from}
                    selected={dateRange}
                    onSelect={setDateRange}
                    numberOfMonths={2}
                  />
                </PopoverContent>
              </Popover>
              <Button variant="outline" size="icon">
                <Filter className="h-4 w-4" />
                <span className="sr-only">筛选</span>
              </Button>
            </div>
            <Button variant="outline" size="sm" className="gap-1">
              <Download className="h-4 w-4" />
              导出数据
            </Button>
          </div>

          <Tabs defaultValue="list">
            <TabsList className="mb-4">
              <TabsTrigger value="list">列表视图</TabsTrigger>
              <TabsTrigger value="calendar">日历视图</TabsTrigger>
            </TabsList>
            <TabsContent value="list">
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>日期</TableHead>
                      <TableHead>班级</TableHead>
                      <TableHead>科目</TableHead>
                      <TableHead>教师</TableHead>
                      <TableHead>时间</TableHead>
                      <TableHead>出勤率</TableHead>
                      <TableHead>注意力</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredHistory.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>{record.date}</TableCell>
                        <TableCell>{record.class}</TableCell>
                        <TableCell>{record.subject}</TableCell>
                        <TableCell>{record.teacher}</TableCell>
                        <TableCell>{record.time}</TableCell>
                        <TableCell>{record.attendanceRate}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <div
                              className={`h-2 w-2 rounded-full ${
                                record.attentionScore > 85
                                  ? "bg-green-500"
                                  : record.attentionScore > 75
                                    ? "bg-yellow-500"
                                    : "bg-red-500"
                              }`}
                            />
                            {record.attentionScore}%
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant={
                              record.status === "优秀" ? "default" : record.status === "良好" ? "secondary" : "outline"
                            }
                          >
                            {record.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <Button variant="ghost" size="sm" className="gap-1">
                            <Eye className="h-4 w-4" />
                            查看详情
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </TabsContent>
            <TabsContent value="calendar">
              <div className="rounded-lg border p-4">
                <div className="mb-4 grid grid-cols-7 gap-4 text-center font-medium">
                  <div>星期一</div>
                  <div>星期二</div>
                  <div>星期三</div>
                  <div>星期四</div>
                  <div>星期五</div>
                  <div>星期六</div>
                  <div>星期日</div>
                </div>
                <div className="grid grid-cols-7 gap-4">
                  {Array.from({ length: 35 }).map((_, index) => {
                    const day = index % 7
                    const isWeekend = day === 5 || day === 6
                    const hasRecords = !isWeekend && Math.random() > 0.5
                    return (
                      <div key={index} className={`min-h-24 rounded-lg border p-2 ${isWeekend ? "bg-gray-50" : ""}`}>
                        <div className="mb-1 text-right text-sm font-medium">{index + 1}</div>
                        {hasRecords && (
                          <div className="space-y-1">
                            <div className="rounded bg-blue-100 px-1 py-0.5 text-xs text-blue-800">
                              数学 08:00 (85%)
                            </div>
                            <div className="rounded bg-green-100 px-1 py-0.5 text-xs text-green-800">
                              语文 10:00 (78%)
                            </div>
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  )
}
